import React, { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, User, Star, Shield, Crown, Award, Play, Image } from 'lucide-react';
import { avatarApi } from '../api';
import type { Avatar, AvatarGroup } from '../api/types';

const AvatarGroupDetail: React.FC = () => {
  const { groupId } = useParams<{ groupId: string }>();
  const navigate = useNavigate();
  const [avatars, setAvatars] = useState<Avatar[]>([]);
  const [group, setGroup] = useState<AvatarGroup | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedAvatar, setSelectedAvatar] = useState<Avatar | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterGender, setFilterGender] = useState<'all' | 'male' | 'female'>('all');
  const [filterPremium, setFilterPremium] = useState<'all' | 'premium' | 'free'>('all');

  const loadGroupData = useCallback(async () => {
    try {
      setLoading(true);

      // 使用简化的API - 直接返回data字段
      const groupsData = await avatarApi.getGroups({ include_public: true, limit: 100 });
      const groupList = groupsData?.rows || [];
      const groupData = groupList.find((g: AvatarGroup) => g.group_id === groupId);

      if (groupData) {
        setGroup(groupData);
      }

      // 获取组内Avatar数据
      const avatarsData = await avatarApi.getGroupAvatars(groupId!, { limit: 100 });
      const avatarsList = avatarsData?.rows || [];
      setAvatars(avatarsList);
    } catch (error) {
      console.error('Failed to load group data:', error);
    } finally {
      setLoading(false);
    }
  }, [groupId]);

  useEffect(() => {
    if (groupId) {
      loadGroupData();
    }
  }, [groupId, loadGroupData]);

  const filteredAvatars = avatars.filter(avatar => {
    const matchesSearch =
      avatar.avatar_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (Array.isArray(avatar.tags) &&
        avatar.tags.some((tag: string) => tag.toLowerCase().includes(searchTerm.toLowerCase())));
    const matchesGender = filterGender === 'all' || avatar.gender === filterGender;
    const matchesPremium =
      filterPremium === 'all' || (filterPremium === 'premium' ? avatar.premium : !avatar.premium);

    return matchesSearch && matchesGender && matchesPremium;
  });

  const getGroupTypeIcon = (type: string) => {
    switch (type) {
      case 'PRIVATE':
        return <Shield className="w-5 h-5 text-blue-400" />;
      case 'PHOTO':
        return <Image className="w-5 h-5 text-purple-400" />;
      case 'PUBLIC':
        return <Crown className="w-5 h-5 text-green-400" />;
      case 'PUBLIC_PHOTO':
        return <Award className="w-5 h-5 text-yellow-400" />;
      case 'COMMUNITY_PHOTO':
        return <Star className="w-5 h-5 text-pink-400" />;
      default:
        return <User className="w-5 h-5 text-gray-400" />;
    }
  };

  const getGroupTypeLabel = (type: string) => {
    switch (type) {
      case 'PRIVATE':
        return '私有组';
      case 'PHOTO':
        return '照片组';
      case 'PUBLIC':
        return '公共组';
      case 'PUBLIC_PHOTO':
        return '公共照片';
      case 'COMMUNITY_PHOTO':
        return '社区照片';
      default:
        return type;
    }
  };

  return (
    <div className="min-h-screen bg-gray-950">
      {/* Header */}
      <div className="bg-gray-900 border-b border-gray-800 mb-6">
        <div className="px-6 py-4">
          <button
            onClick={() => navigate('/avatars')}
            className="flex items-center space-x-2 text-gray-400 hover:text-white transition-colors mb-4 cursor-pointer"
          >
            <ArrowLeft className="w-5 h-5" />
            <span>返回Avatar组列表</span>
          </button>

          {group && (
            <div className="flex items-start space-x-4">
              <img
                src={group.preview_image}
                alt={group.name}
                className="w-20 h-20 rounded-lg object-cover border border-gray-700"
              />
              <div className="flex-1">
                <div className="flex items-center space-x-3 mb-2">
                  <h1 className="text-2xl font-bold text-white">{group.name}</h1>
                  <div className="flex items-center space-x-2 bg-gray-800 px-3 py-1 rounded-full">
                    {getGroupTypeIcon(group.group_type)}
                    <span className="text-sm text-gray-300">
                      {getGroupTypeLabel(group.group_type)}
                    </span>
                  </div>
                  {group.train_status && (
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-medium ${
                        group.train_status === 'ready'
                          ? 'bg-green-500/10 text-green-400 border border-green-500/20'
                          : group.train_status === 'training'
                            ? 'bg-yellow-500/10 text-yellow-400 border border-yellow-500/20'
                            : 'bg-gray-500/10 text-gray-400 border border-gray-500/20'
                      }`}
                    >
                      {group.train_status === 'ready'
                        ? '已训练'
                        : group.train_status === 'training'
                          ? '训练中'
                          : group.train_status}
                    </span>
                  )}
                </div>
                <p className="text-gray-400">
                  包含 <span className="text-cyan-400 font-semibold">{group.num_looks}</span>{' '}
                  个Avatar形象
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Filters */}
      <div className="px-6 mb-6">
        <div className="flex flex-wrap gap-4">
          <div className="flex-1 min-w-[300px]">
            <input
              type="text"
              placeholder="搜索Avatar名称或标签..."
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="w-full px-4 py-2 bg-gray-900 border border-gray-800 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-cyan-500"
            />
          </div>

          <select
            value={filterGender}
            onChange={e => setFilterGender(e.target.value as 'all' | 'male' | 'female')}
            className="px-4 py-2 bg-gray-900 border border-gray-800 rounded-lg text-white focus:outline-none focus:border-cyan-500"
          >
            <option value="all">所有性别</option>
            <option value="male">男性</option>
            <option value="female">女性</option>
          </select>

          <select
            value={filterPremium}
            onChange={e => setFilterPremium(e.target.value as 'all' | 'premium' | 'free')}
            className="px-4 py-2 bg-gray-900 border border-gray-800 rounded-lg text-white focus:outline-none focus:border-cyan-500"
          >
            <option value="all">所有类型</option>
            <option value="premium">Premium</option>
            <option value="free">免费</option>
          </select>
        </div>

        <div className="mt-4 text-sm text-gray-400">
          显示 <span className="text-cyan-400 font-semibold">{filteredAvatars.length}</span> /{' '}
          {avatars.length} 个Avatar
        </div>
      </div>

      {/* Avatar Grid */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-500"></div>
        </div>
      ) : filteredAvatars.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-64 text-gray-400">
          <User className="w-16 h-16 mb-4 opacity-50" />
          <p className="text-lg font-medium">没有找到Avatar</p>
          <p className="text-sm mt-2">尝试调整筛选条件</p>
        </div>
      ) : (
        <div className="px-6 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
          {filteredAvatars.map(avatar => (
            <div
              key={avatar.avatar_id}
              className="bg-gray-900 border border-gray-800 rounded-lg overflow-hidden hover:border-cyan-500/50 transition-all cursor-pointer group"
              onClick={() => setSelectedAvatar(avatar)}
            >
              <div className="relative aspect-square">
                <img
                  src={avatar.preview_image_url}
                  alt={avatar.avatar_name}
                  className="w-full h-full object-cover"
                />

                {/* Premium Badge */}
                {avatar.premium && (
                  <div className="absolute top-2 right-2 bg-gradient-to-r from-yellow-500 to-orange-500 px-2 py-1 rounded-full">
                    <span className="text-xs font-bold text-white">PRO</span>
                  </div>
                )}

                {/* Gender Badge */}
                <div className="absolute top-2 left-2 bg-black/50 backdrop-blur-sm px-2 py-1 rounded-full">
                  <span className="text-xs text-white">
                    {avatar.gender === 'male' ? '♂' : '♀'}
                  </span>
                </div>

                {/* Hover Overlay */}
                <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex flex-col justify-end p-3">
                  <button className="w-full bg-cyan-500 hover:bg-cyan-600 text-white py-2 rounded-lg flex items-center justify-center space-x-2 transition-colors">
                    <Play className="w-4 h-4" />
                    <span className="text-sm font-medium">预览</span>
                  </button>
                </div>
              </div>

              <div className="p-3">
                <h3 className="font-medium text-white text-sm truncate">{avatar.avatar_name}</h3>
                {Array.isArray(avatar.tags) && avatar.tags.length > 0 && (
                  <div className="mt-2 flex flex-wrap gap-1">
                    {Array.isArray(avatar.tags) &&
                      avatar.tags.slice(0, 2).map((tag: string, index: number) => (
                        <span
                          key={index}
                          className="text-xs bg-gray-800 text-gray-400 px-2 py-0.5 rounded"
                        >
                          {tag}
                        </span>
                      ))}
                    {avatar.tags.length > 2 && (
                      <span className="text-xs text-gray-500">+{avatar.tags.length - 2}</span>
                    )}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Avatar Detail Modal */}
      {selectedAvatar && (
        <div
          className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          onClick={() => setSelectedAvatar(null)}
        >
          <div
            className="bg-gray-900 border border-gray-800 rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden"
            onClick={e => e.stopPropagation()}
          >
            <div className="flex">
              {/* Preview Section */}
              <div className="w-1/2 bg-black">
                {selectedAvatar.preview_video_url ? (
                  <video
                    src={selectedAvatar.preview_video_url}
                    className="w-full h-full object-contain"
                    controls
                    autoPlay
                    loop
                  />
                ) : (
                  <img
                    src={selectedAvatar.preview_image_url}
                    alt={selectedAvatar.avatar_name}
                    className="w-full h-full object-contain"
                  />
                )}
              </div>

              {/* Details Section */}
              <div className="w-1/2 p-6">
                <div className="flex justify-between items-start mb-4">
                  <h2 className="text-2xl font-bold text-white">{selectedAvatar.avatar_name}</h2>
                  <button
                    onClick={() => setSelectedAvatar(null)}
                    className="text-gray-400 hover:text-white cursor-pointer"
                  >
                    ✕
                  </button>
                </div>

                <div className="space-y-4">
                  <div>
                    <p className="text-sm text-gray-400 mb-1">Avatar ID</p>
                    <p className="text-white font-mono text-sm">{selectedAvatar.avatar_id}</p>
                  </div>

                  <div>
                    <p className="text-sm text-gray-400 mb-1">性别</p>
                    <p className="text-white">
                      {selectedAvatar.gender === 'male' ? '男性' : '女性'}
                    </p>
                  </div>

                  {selectedAvatar.type && (
                    <div>
                      <p className="text-sm text-gray-400 mb-1">类型</p>
                      <p className="text-white">{selectedAvatar.type}</p>
                    </div>
                  )}

                  <div>
                    <p className="text-sm text-gray-400 mb-1">Premium状态</p>
                    <span
                      className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${
                        selectedAvatar.premium
                          ? 'bg-gradient-to-r from-yellow-500/20 to-orange-500/20 text-yellow-400 border border-yellow-500/30'
                          : 'bg-gray-800 text-gray-400'
                      }`}
                    >
                      {selectedAvatar.premium ? 'Premium Avatar' : '免费使用'}
                    </span>
                  </div>

                  {Array.isArray(selectedAvatar.tags) && selectedAvatar.tags.length > 0 && (
                    <div>
                      <p className="text-sm text-gray-400 mb-2">标签</p>
                      <div className="flex flex-wrap gap-2">
                        {Array.isArray(selectedAvatar.tags) &&
                          selectedAvatar.tags.map((tag: string, index: number) => (
                            <span
                              key={index}
                              className="bg-gray-800 text-gray-300 px-3 py-1 rounded-lg text-sm"
                            >
                              {tag}
                            </span>
                          ))}
                      </div>
                    </div>
                  )}

                  <div className="pt-4 space-y-2">
                    <button className="w-full bg-cyan-500 hover:bg-cyan-600 text-white py-3 rounded-lg font-medium transition-colors">
                      使用此Avatar创建视频
                    </button>
                    <button className="w-full bg-gray-800 hover:bg-gray-700 text-white py-3 rounded-lg font-medium transition-colors">
                      查看Avatar详情
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AvatarGroupDetail;
